import { defineStore } from 'pinia'
import { RouteRecordRaw, RouteRecordName } from 'vue-router'
//定义store
export const keepAliveStore = defineStore('keepAliveStore', {
	state: () => {
		return {
			cacheList: [] as any,
			excacheList: [] as any
		}
	},
	getters: {
		getCacheList(state) {
			return state.cacheList
		},
		getExcacheList(state) {
			return state.excacheList
		}
	},
	actions: {
		setCacheList(router: any) {
			return new Promise((resolve, reject) => {
				this.cacheList = generateRoutes(router)
				resolve(this.cacheList)
			})
		},
		setExcacheList(router: any) {
			return new Promise((resolve, reject) => {
				this.excacheList = generateExRoutes(router)
				resolve(this.excacheList)
			})
		}
	}
})
//动态生成路由
export const generateRoutes = (_route: RouteRecordRaw[]) => {
	//定义接收生成的菜单
	const res: Array<RouteRecordName> = []
	_route.forEach((item) => {
		if (item.children && item.children.length > 0) {
			item.children.map((it) => {
				it.meta?.keepAlive && it.name && res.push(it.name)
			})
		}
		item.meta?.keepAlive && item.name && res.push(item.name)
	})
	return res
}
export const generateExRoutes = (_route: RouteRecordRaw[]) => {
	//定义接收生成的菜单
	const res: Array<RouteRecordName> = []
	_route.forEach((item) => {
		if (item.children && item.children.length > 0) {
			item.children.map((it) => {
				!it.meta?.keepAlive && it.name && res.push(it.name)
			})
		}
		!item.meta?.keepAlive && item.name && res.push(item.name)
	})
	return res
}